﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Xml;

namespace Powerless_View.Util
{
    public class HttpGetter
    {
        public XDocument GetXDocResponse(string url)
        {
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // we will read data via the response stream
            try
            {
                using (Stream resStream = response.GetResponseStream())
                {
                    return XDocument.Load(resStream);
                }
            }
            catch (XmlException)
            {
                return new XDocument();
            }
        }

        public MemoryStream GetResponse(string url)
        {
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            
            // execute the request
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            // we will read data via the response stream
            using (Stream resStream = response.GetResponseStream())
            {
                MemoryStream mem = new MemoryStream();
                CopyStream(resStream, mem);
                return mem;
            }
        }

        private static void CopyStream(Stream input, Stream output)
        {
            byte[] b = new byte[32768];
            int r;
            while ((r = input.Read(b, 0, b.Length)) > 0)
                output.Write(b, 0, r);
        }
    }
}
